/*
 * Copyright (C) 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.xmpp;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.xmppService.IXmppService;
import com.google.android.xmppService.IXmppSession;

public class XMPPSender extends Activity {
    private static final String LOG_TAG = "XMPPSender";

    IXmppSession mXmppSession = null;
    EditText mUsernameField;
    EditText mTextField;
    Button mSendButton;

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(R.layout.main);

        mUsernameField = (EditText) findViewById(R.id.username);
        mUsernameField.setOnClickListener(mOnClickListener);
        mUsernameField.requestFocus();

        mTextField = (EditText) findViewById(R.id.message_text);

        mSendButton = (Button) findViewById(R.id.send);
        mSendButton.setOnClickListener(mOnClickListener);
        mSendButton.setEnabled(false);

        bindXmppService();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mConnection);
    }

    private void bindXmppService() {
        bindService((new Intent()).setComponent(
                com.google.android.xmppService.XmppConstants.XMPP_SERVICE_COMPONENT),
                null, mConnection, 0);
    }

    private boolean isValidUsername(String username) {
        if (TextUtils.isEmpty(username)) {
            return false;
        }

        if (username.indexOf('@') == -1) {
            return false;
        }

        return true;
    }

    private void logMessage(CharSequence msg) {
        NotificationManager nm = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);

        nm.notifyWithText(123, msg, NotificationManager.LENGTH_LONG, null);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the XmppService has been
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            IXmppService xmppService = IXmppService.Stub.asInterface(service);

            try {
                mXmppSession = xmppService.getDefaultSession();
                if (mXmppSession == null) {
                    // this should not happen.
                    logMessage(getText(R.string.xmpp_session_not_found));
                    return;
                }
            } catch (DeadObjectException ex) {
                Log.e(LOG_TAG, "caught " + ex);
                logMessage(getText(R.string.found_stale_xmpp_service));
            }

            mSendButton.setEnabled(true);
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mXmppSession = null;
            mSendButton.setEnabled(false);
        }
    };

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            if (v == mUsernameField) {
                mSendButton.requestFocus();
            } else {
                // use XmppService to send data message to someone
                String username = mUsernameField.getText().toString();
                if (!isValidUsername(username)) {
                    logMessage(getText(R.string.invalid_username));
                    return;
                }

                if (mXmppSession == null) {
                    logMessage(getText(R.string.xmpp_service_not_connected));
                    return;
                }

                try {
                    mXmppSession.sendTextMessage(username, 0, mTextField.getText().toString());
                } catch (DeadObjectException ex) {
                    Log.e(LOG_TAG, "caught " + ex);
                    logMessage(getText(R.string.found_stale_xmpp_service));
                    mXmppSession = null;
                    bindXmppService();
                }
            }
        }
    };

}
